# ============================================
# 学生信息管理系统API测试脚本
# ============================================

$baseUrl = "http://localhost:3001/api/students"

Write-Host "========================================" -ForegroundColor Cyan
Write-Host "  学生信息管理系统API测试" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""

# 检查服务器是否运行
Write-Host "[检查] 验证后端服务状态..." -ForegroundColor Yellow
try {
    $health = Invoke-RestMethod -Uri "http://localhost:3001/health" -Method GET
    Write-Host "✓ 后端服务正常运行" -ForegroundColor Green
    Write-Host "  时间: $($health.timestamp)" -ForegroundColor Gray
} catch {
    Write-Host "✗ 后端服务未启动，请先运行: cd backend; npm run dev" -ForegroundColor Red
    exit 1
}

# 1. 批量创建测试数据
Write-Host "`n[测试1] 批量创建学生信息..." -ForegroundColor Yellow
$students = @{
    students = @(
        @{ 
            studentNo = "20240001"
            name = "张三"
            className = "计算机一班"
            grade = 95
            email = "zhangsan@example.com"
            gender = "male"
        },
        @{ 
            studentNo = "20240002"
            name = "李四"
            className = "计算机一班"
            grade = 88
            email = "lisi@example.com"
            gender = "male"
        },
        @{ 
            studentNo = "20240003"
            name = "王五"
            className = "计算机一班"
            grade = 72
            email = "wangwu@example.com"
            gender = "female"
        },
        @{ 
            studentNo = "20240004"
            name = "赵六"
            className = "计算机二班"
            grade = 55
            email = "zhaoliu@example.com"
            gender = "male"
        },
        @{ 
            studentNo = "20240005"
            name = "钱七"
            className = "计算机二班"
            grade = 91
            email = "qianqi@example.com"
            gender = "female"
        }
    )
} | ConvertTo-Json -Depth 3

try {
    $result = Invoke-RestMethod -Uri "$baseUrl/batch" -Method POST -Body $students -ContentType "application/json"
    Write-Host "✓ 成功导入 $($result.data.inserted) 条数据" -ForegroundColor Green
} catch {
    if ($_.Exception.Message -like "*409*") {
        Write-Host "! 部分学号已存在，跳过导入" -ForegroundColor Yellow
    } else {
        Write-Host "✗ 导入失败: $($_.Exception.Message)" -ForegroundColor Red
    }
}

# 2. 查询学生列表
Write-Host "`n[测试2] 查询学生列表..." -ForegroundColor Yellow
try {
    $result = Invoke-RestMethod -Uri "$baseUrl?page=1&limit=10" -Method GET
    Write-Host "✓ 共查询到 $($result.data.pagination.total) 条记录" -ForegroundColor Green
    Write-Host "  当前页: $($result.data.pagination.page)/$($result.data.pagination.pages)" -ForegroundColor Gray
    
    if ($result.data.students.Count -gt 0) {
        $script:firstStudentId = $result.data.students[0].id
        Write-Host "  第一个学生: $($result.data.students[0].name) (学号: $($result.data.students[0].studentNo))" -ForegroundColor Gray
    }
} catch {
    Write-Host "✗ 查询失败: $($_.Exception.Message)" -ForegroundColor Red
}

# 3. 按班级筛选
Write-Host "`n[测试3] 按班级筛选（计算机一班）..." -ForegroundColor Yellow
try {
    $result = Invoke-RestMethod -Uri "$baseUrl?className=计算机一班" -Method GET
    Write-Host "✓ 找到 $($result.data.pagination.total) 个学生" -ForegroundColor Green
} catch {
    Write-Host "✗ 筛选失败: $($_.Exception.Message)" -ForegroundColor Red
}

# 4. 按成绩范围筛选
Write-Host "`n[测试4] 按成绩范围筛选（80-100分）..." -ForegroundColor Yellow
try {
    $result = Invoke-RestMethod -Uri "$baseUrl?minGrade=80&maxGrade=100" -Method GET
    Write-Host "✓ 找到 $($result.data.pagination.total) 个优秀学生" -ForegroundColor Green
} catch {
    Write-Host "✗ 筛选失败: $($_.Exception.Message)" -ForegroundColor Red
}

# 5. 关键词搜索
Write-Host "`n[测试5] 关键词搜索（张三）..." -ForegroundColor Yellow
try {
    $result = Invoke-RestMethod -Uri "$baseUrl?keyword=张三" -Method GET
    Write-Host "✓ 找到 $($result.data.pagination.total) 条匹配记录" -ForegroundColor Green
} catch {
    Write-Host "✗ 搜索失败: $($_.Exception.Message)" -ForegroundColor Red
}

# 6. 获取单个学生详情
if ($script:firstStudentId) {
    Write-Host "`n[测试6] 获取学生详情..." -ForegroundColor Yellow
    try {
        $result = Invoke-RestMethod -Uri "$baseUrl/$($script:firstStudentId)" -Method GET
        Write-Host "✓ 获取成功: $($result.data.name)" -ForegroundColor Green
        Write-Host "  学号: $($result.data.studentNo)" -ForegroundColor Gray
        Write-Host "  班级: $($result.data.className)" -ForegroundColor Gray
        Write-Host "  成绩: $($result.data.grade)" -ForegroundColor Gray
    } catch {
        Write-Host "✗ 获取失败: $($_.Exception.Message)" -ForegroundColor Red
    }
}

# 7. 更新学生信息
if ($script:firstStudentId) {
    Write-Host "`n[测试7] 更新学生成绩..." -ForegroundColor Yellow
    $updateBody = @{ grade = 98 } | ConvertTo-Json
    try {
        $result = Invoke-RestMethod -Uri "$baseUrl/$($script:firstStudentId)" -Method PUT -Body $updateBody -ContentType "application/json"
        Write-Host "✓ 更新成功，新成绩: $($result.data.grade)" -ForegroundColor Green
    } catch {
        Write-Host "✗ 更新失败: $($_.Exception.Message)" -ForegroundColor Red
    }
}

# 8. 获取成绩统计（计算机一班）
Write-Host "`n[测试8] 获取成绩统计（计算机一班）..." -ForegroundColor Yellow
try {
    $result = Invoke-RestMethod -Uri "$baseUrl/analysis/statistics?className=计算机一班" -Method GET
    Write-Host "✓ 统计数据获取成功" -ForegroundColor Green
    Write-Host "  班级: $($result.data.className)" -ForegroundColor Gray
    Write-Host "  总人数: $($result.data.basic.totalStudents)" -ForegroundColor Gray
    Write-Host "  平均分: $([math]::Round($result.data.basic.avgGrade, 2))" -ForegroundColor Gray
    Write-Host "  最高分: $($result.data.basic.maxGrade)" -ForegroundColor Gray
    Write-Host "  最低分: $($result.data.basic.minGrade)" -ForegroundColor Gray
    Write-Host "  成绩分布:" -ForegroundColor Gray
    Write-Host "    优秀(90-100): $($result.data.distribution.excellent.count)人 ($($result.data.distribution.excellent.percentage)%)" -ForegroundColor Gray
    Write-Host "    良好(80-89): $($result.data.distribution.good.count)人 ($($result.data.distribution.good.percentage)%)" -ForegroundColor Gray
    Write-Host "    及格(60-79): $($result.data.distribution.pass.count)人 ($($result.data.distribution.pass.percentage)%)" -ForegroundColor Gray
    Write-Host "    不及格(0-59): $($result.data.distribution.fail.count)人 ($($result.data.distribution.fail.percentage)%)" -ForegroundColor Gray
} catch {
    Write-Host "✗ 统计失败: $($_.Exception.Message)" -ForegroundColor Red
}

# 9. 生成AI班级分析报告
Write-Host "`n[测试9] 生成AI班级分析报告..." -ForegroundColor Yellow
$reportBody = @{ className = "计算机一班" } | ConvertTo-Json
try {
    $result = Invoke-RestMethod -Uri "$baseUrl/analysis/ai-report" -Method POST -Body $reportBody -ContentType "application/json"
    Write-Host "✓ AI报告生成成功" -ForegroundColor Green
    Write-Host "`n--- AI分析报告 ---" -ForegroundColor Cyan
    Write-Host "  总体评价: $($result.data.analysis.overallAssessment)" -ForegroundColor White
    Write-Host "  平均分: $($result.data.analysis.averageScore)" -ForegroundColor White
    Write-Host "  建议:" -ForegroundColor White
    foreach ($suggestion in $result.data.analysis.suggestions) {
        Write-Host "    - $suggestion" -ForegroundColor Gray
    }
    Write-Host "--- 报告结束 ---`n" -ForegroundColor Cyan
} catch {
    Write-Host "✗ 生成失败: $($_.Exception.Message)" -ForegroundColor Red
}

# 10. 生成AI个人分析报告
if ($script:firstStudentId) {
    Write-Host "`n[测试10] 生成AI个人分析报告..." -ForegroundColor Yellow
    $personalReportBody = @{ studentId = $script:firstStudentId } | ConvertTo-Json
    try {
        $result = Invoke-RestMethod -Uri "$baseUrl/analysis/ai-report" -Method POST -Body $personalReportBody -ContentType "application/json"
        Write-Host "✓ AI个人报告生成成功" -ForegroundColor Green
        Write-Host "`n--- AI个人分析报告 ---" -ForegroundColor Cyan
        Write-Host "  学生: $($result.data.student.name) ($($result.data.student.studentNo))" -ForegroundColor White
        Write-Host "  成绩: $($result.data.student.grade) ($($result.data.student.gradeLevel))" -ForegroundColor White
        
        if ($result.data.analysis.strengths.Count -gt 0) {
            Write-Host "  优势:" -ForegroundColor White
            foreach ($strength in $result.data.analysis.strengths) {
                Write-Host "    - $strength" -ForegroundColor Gray
            }
        }
        
        if ($result.data.analysis.improvements.Count -gt 0) {
            Write-Host "  待改进:" -ForegroundColor White
            foreach ($improvement in $result.data.analysis.improvements) {
                Write-Host "    - $improvement" -ForegroundColor Gray
            }
        }
        
        Write-Host "  建议:" -ForegroundColor White
        foreach ($suggestion in $result.data.analysis.suggestions) {
            Write-Host "    - $suggestion" -ForegroundColor Gray
        }
        
        Write-Host "  激励语: $($result.data.analysis.motivationalQuote)" -ForegroundColor Yellow
        Write-Host "--- 报告结束 ---`n" -ForegroundColor Cyan
    } catch {
        Write-Host "✗ 生成失败: $($_.Exception.Message)" -ForegroundColor Red
    }
}

# 测试总结
Write-Host "`n========================================" -ForegroundColor Cyan
Write-Host "  API测试完成！" -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "`n所有接口测试已完成，请查看上述结果。" -ForegroundColor White
Write-Host "`n下一步操作：" -ForegroundColor Yellow
Write-Host "1. 在Postman中测试接口（参考 STUDENT_API_GUIDE.md）" -ForegroundColor White
Write-Host "2. 开始前端开发（cd frontend; npm run dev）" -ForegroundColor White
Write-Host "3. 提交代码到Git仓库" -ForegroundColor White
Write-Host ""
